package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.MealitemDAO;
import com.neusoft.EYSystem.po.Mealitem;
import com.neusoft.EYSystem.po.NursingProject;
import com.neusoft.EYSystem.po.PageResponseBean;
import com.neusoft.EYSystem.service.MealitemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MealitemServiceImpl implements MealitemService {

    // ✅ 工具方法：判断是否为合法字符串（排除 null、空串、"null"）
    private boolean isValid(String value) {
        return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim());
    }

    @Autowired
    private MealitemDAO mealitemDAO;

    @Override
    public Integer deleteStatusById(Mealitem mealitem) {
        UpdateWrapper<Mealitem> uw = new UpdateWrapper<>();
        uw.eq("mealitem_id", mealitem.getMealitemId());
        mealitem.setStatus("0");
        return mealitemDAO.update(mealitem, uw);
    }

    @Override
    public PageResponseBean<List<Mealitem>> pageMealitem(Long cur, Long number, Mealitem mealitem) {
        // 1. 创建分页对象（第cur页，每页number条记录）
        IPage<Mealitem> page = new Page<>(cur, number);

        // 2. 构造查询条件的包装器，用于动态拼接SQL中的WHERE子句
        QueryWrapper<Mealitem> wrapper = new QueryWrapper<>();

        // 5. 判断是否传入 name 字段，进行模糊匹配 name LIKE '%xxx%'
        if (isValid(mealitem.getName())) {
            wrapper.like("name", mealitem.getName()); // 若已有条件，则使用 OR name LIKE
        }

        IPage<Mealitem> result = mealitemDAO.selectPage(page, wrapper);

        // 8. 获取分页结果的数据列表和总条数
        List<Mealitem> list = result.getRecords();
        long total = result.getTotal();
        // 9. 封装并返回统一的响应对象 PageResponseBean
        PageResponseBean<List<Mealitem>> rb;
        if (total > 0) {
            rb = new PageResponseBean<>(list); // 查询成功
            rb.setTotal(total);
        } else {
            rb = new PageResponseBean<>(500, "无膳食品类数据"); // ⚠️ 不推荐使用500，查无数据不代表错误（建议返回空列表）
        }

        return rb;
    }
}
